package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.entity.Worker;
import com.example.haoqisystem.request.CreateWorkerRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.respository.TeacherRepository;
import com.example.haoqisystem.respository.WorkerRespository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor(onConstructor_ =@__(@Autowired))
@Slf4j
public class WorkerService {
    private final WorkerRespository workerRespository;
    private final TeacherRepository teacherRepository;
    //新增职工
    public BaseResponse<Worker> add(CreateWorkerRequest request) {
        //验证该账号是否存在
        if(workerRespository.findByAccountAndDeletedFalse(request.getAccount()).isPresent()){
            return new BaseResponse<>("该用户账户已存在！",false,null);
        }
        //验证密码
        if(!isPassword(request.getPassword())){
            return new BaseResponse<>("密码错误！",false,null);
        }
        try {
            Worker worker = new Worker();
            BeanUtil.copyProperties(request, worker, CopyOptions.create().setIgnoreNullValue(true));
            Worker worker1 = workerRespository.save(worker);
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true, worker1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }


    public boolean isPassword(String pwd){
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,16}$";
        return pwd.matches((regex));
    }


    //职工登录
    public BaseResponse<Worker> login(String account, String password, String role, Integer roleId) {
            Optional<Worker> workerOptional= workerRespository.findByAccountAndRoleAndRoleIdAndDeletedFalse(account
                    ,role,roleId);
            if(!workerOptional.isPresent()){
                return new BaseResponse<>("该账户不存在！",false,null);
        }
            Worker worker=workerOptional.get();
            if(!password.equals(worker.getPassword())){
                return new BaseResponse<>("密码错误！",false,null);
            }
            return new BaseResponse<>("登录成功!",true,worker);
    }

    //查询职工列表
    public BaseResponse<List<Worker>> list(String role) {
        try{
            Specification<Worker> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(role!=null&&!role.equals("")){
                    String roleLike="%"+role+"%";
                    predicates.add(builder.like(root.get("role"),roleLike));
                }
                predicates.add(builder.equal(root.get("deleted"),false));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<Worker> list= workerRespository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),true,null);
        }
    }

    //删除职工
    public BaseResponse<String> delete(Long id) {
        try{
            Optional<Worker> optionalWorker=workerRespository.findByIdAndDeletedFalse(id);
            if(!optionalWorker.isPresent()){
                return new BaseResponse<>(ConstUtil.DELETED_FALSE,false,"该职工不存在或者已被逻辑删除");
            }
            Worker worker=optionalWorker.get();
            worker.setDeleted(true);
            workerRespository.save(worker);
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,"删除成功！");
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,"删除shibai！");
        }
    }
}
